package com.yeb.server.config.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 权限控制，判断当前用户是否具备指定的角色
 * @Author liushizhong
 * @Date 2021/10/6 14:42
 * @Version 1.0
 */

@Component
public class CustomUrlDecisionManager implements AccessDecisionManager { // 访问决策管理器
    @Override
    // 用户的角色在 authentication里，资源需要的角色在 collection 中
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection)
            throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute : collection) {
            //当前url所需角色
            String needRole = configAttribute.getAttribute();
            //判断角色是否是登入即可访问的角色，此角色在CustomFilter中设置
            if("ROLE_LOGIN".equals(needRole)){
                //判断是否登入
                if(authentication instanceof AnonymousAuthenticationToken){ // 匿名登入
                    throw new AccessDeniedException("尚未登入，请登入！");
                }else{
                    return;
                }
            }
            //判断用户角色是否是url需要的角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if(authority.getAuthority().equals(needRole)){
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
